﻿using Common;
using NB.MGJ.Common;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.Market;
using NB.MGJ.Service.Config;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebAppModel;
using WxPayAPI;
using System.Text;
using System.Security.Cryptography;

namespace NB.MGJ.WebWap.Controllers
{
    public class PreViewController : Controller
    {
        MarketService _MarketService = new MarketService();
        TheWinningService _the = new TheWinningService();

        public ActionResult ErrorView() 
        {
            return View();
        }


        private string GetSignature(string jsapi_ticket, string noncestr, string timestamp, string url)
        {
            var string1Builder = new StringBuilder();
            string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(noncestr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
            string string1 = string1Builder.ToString();
            WXPortController wx = new WXPortController();
            return wx.SHA1(string1.ToString());
        }

        private string Sha1(string orgStr, string encode = "UTF-8")
        {
            var sha1 = new SHA1Managed();
            var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
            byte[] resultHash = sha1.ComputeHash(sha1bytes);
            string sha1String = BitConverter.ToString(resultHash).ToLower();
            sha1String = sha1String.Replace("-", "");
            return sha1String;
        }

        private string GetSignature(string jsapi_ticket, string noncestr, long timestamp, string url, out string string1)
        {
            var string1Builder = new StringBuilder();
            string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(noncestr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
            string1 = string1Builder.ToString();
            return Sha1(string1);
        }

        //
        // GET: /PreView/
        public ActionResult ActivityHome()
        {
            //是否获取用户信息 似乎需要进行判断
            try
            {
                string code = Request["code"];
                config_WX wxConfigModel = (Session["wxConfig"] as config_WX);
                var user = OAuthApi.GetAccessToken(wxConfigModel.AppId, wxConfigModel.AppSecret, code);
                var userinfo = OAuthApi.GetUserInfo(user.access_token, user.openid);
                ViewBag.Aid = Request["aId"];
                //添加用户扫码信息
                UserScanQRInfoModel userQR = new UserScanQRInfoModel();
                userQR.WXName = userinfo.nickname;
                userQR.Aid = int.Parse(Request["aId"]);
                userQR.Eid = wxConfigModel.Eid.Value;
                Session["user"] = userQR;

                WXPortController wx = new WXPortController();
                int nonceStrLength = 16;
                string accessToken = wx.GetAccessToken(wxConfigModel.AppId, wxConfigModel.AppSecret)["access_token"].ToString();
                string jsapi_ticket = wx.GetJsapi_ticket(accessToken)["ticket"].ToString();
                string timestamp = wx.GetTimestamp();
                string nonceStr = wx.GetRnd(nonceStrLength, true, true, true, false, "");
                string url = Request.Url.AbsoluteUri.ToString();
                //拼接字符串
                string singnature = GetSignature(jsapi_ticket, nonceStr, timestamp, url);

                ViewBag.appId = wxConfigModel.AppId;
                ViewBag.timestamp = timestamp;
                ViewBag.nonceStr = nonceStr;
                ViewBag.signature = singnature;
                return View();

                //UserScanQRInfoModel user = new UserScanQRInfoModel();
                //user.WXName = "测试";
                //ViewBag.Aid = Request["aId"];
                //user.Aid = Convert.ToInt32(Request["aId"]);
                //Session["user"] = user;
                //return View();
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("ActivityHome错误", ex.ToString());
                return View("ErrorView");
            }
        }
        public ActionResult ActivityPrizeState()
        {
            return View();
        }
        public ActionResult GetError(int Tid = 0)
        {
            ViewBag.Tid = Tid;
            return View();
        }
        public ActionResult GetErrorHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetError.Replace(" ", "+");
            return Json(data);
        }
        public ActionResult GetRank(int Tid)
        {
            ViewBag.Tid = Tid;
            return View();
        }
        public ActionResult GetRankHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetRank.Replace(" ", "+");
            return Json(data);
        }
        //活动说明
        public ActionResult ActivityPrizeState(int Tid)
        {
            ViewBag.Tid = Tid;
            return View();
        }
        public ActionResult ActivityStateHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetRank.Replace(" ", "+");
            return Json(data);
        }
        public ActionResult Verification(int awId = 0, int Aid = 0, decimal Denomination = 0)
        {
            ViewBag.Aid = Aid;
            ViewBag.awId = awId;
            ViewBag.Denomination = Denomination;
            ViewBag.Time=DateTime.Now;
            return View();
        }
        public ActionResult VerificationHtml(int aId)
        {
            var model = _MarketService.GetTemplateByAid(aId);
            string data = model.Verification.Replace(" ", "+");
            return Json(data);
        }
        //获取模板
        public ActionResult GetTemplate(string address, int aId = 0)
        {
            var activity = _MarketService.GetActivityById(aId);
            Hashtable ht = new Hashtable();
            if (activity != null && activity.IsLimitArea == 1 && !string.IsNullOrEmpty(address))
            {
                var adds = address.Split(',');
                var province = adds.Length > 0 ? adds[0] : "";
                var city = adds.Length > 1 ? adds[1] : "";
                var actProvince = activity.Privance == null ? "" : activity.Privance;
                var actCity = activity.City == null ? "" : activity.City;
                if (actCity.IndexOf(city) == -1 && actProvince.IndexOf(province) == -1)
                {  //当前网络地址不在活动范围
                    ht.Add("IsTrue", "0");//没有活动
                    return Json(ht, JsonRequestBehavior.AllowGet);
                }
            }
            var model = _MarketService.GetTemplateByAid(aId);
            ht.Add("html", model.ActivityHome.Replace(" ", "+"));
            ht.Add("tid", model.ID);
            UserScanQRInfoModel user =   Session["user"] as UserScanQRInfoModel;
            user.TId = model.ID;
            Session["user"] = user;
            ht.Add("IsTrue", "1");
            ht.Add("ActivityType", activity.ActivityType);
            return Json(ht);
        }
        /// <summary>
        /// 根据活动编号 中奖项
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAwards(int aId = 0)
        {
            try
            {
                List<Marketing_Awards> list = _MarketService.GetAwards_Aid(aId);
                //随机数
                Random random = new Random();
                int awardIndex = random.Next(10000);
                double index = 0;
                double end = 0;
                Marketing_Awards award = new Marketing_Awards();
                foreach (var item in list)
                {
                    end += double.Parse(item.Rate.ToString()) * 100;
                    if (index <= awardIndex && awardIndex < end)//中奖范围
                    {
                        if (item.ResidueNums <= 0)//奖项剩余数量
                        {
                            awardIndex = random.Next(10000);
                            index = 0;
                            end = 0;
                            continue;
                        }
                        award = item;//抽中的奖项类别
                        break;
                    }
                    index = end;
                }
                if (award.Id != 0)
                {
                    int jackpotId = award.JackpotID;//指定奖项
                    Marketing_Jackpot jackpot = _MarketService.GetJackpotModel(jackpotId);
                    //中奖类型 
                    int type = jackpot.Type.Value;
                    //如果是红包类型
                    if (type == 1)
                    {
                        if (jackpot.CouponType == 0) //运气红包
                        {
                            //取最大金额和最小金额之间的随机数
                            double Num = (double)(jackpot.MaxDenomination - jackpot.MinDenomination);
                            double denom = Math.Round(random.NextDouble() * Num, 2);
                            jackpot.Denomination = (decimal)denom + jackpot.MinDenomination;
                        }
                        else//普通红包
                        {

                        }
                    }
                    award.type = type;
                    award.Denomination = jackpot.Denomination;
                }
                else
                {
                    award.ActivityId = aId;
                    award.Id = 0;
                    award.Congrats = "没有中到奖品！";
                    award.EnterpriseName = list[0].EnterpriseName;
                    award.Sequence = 0;
                    award.Denomination = -1;
                }
                UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
                user.Denomination = award.Denomination;
                user.AwId = award.Id;
                Session["user"] = user;
                return Json(award, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("GetAwardsErr", ex.ToString());
                throw;
            }
        }
        //中奖明细
        public JsonResult GetTheWinningList()
        {
            PagedList<Marketing_TheWinning> list = new PagedList<Marketing_TheWinning>();

            Marketing_TheWinning theWinning0 = new Marketing_TheWinning();
            theWinning0.Nickname = "张小明";
            theWinning0.Denomination = Convert.ToDecimal(10.00);
            theWinning0.Time = DateTime.Now;
            theWinning0.HeadImgUrl = "/app/Content/Images/redpack/xiaoming.jpg";
            list.Add(theWinning0);
            Marketing_TheWinning theWinning1 = new Marketing_TheWinning();
            theWinning1.Nickname = "李小红";
            theWinning1.Denomination =Convert.ToDecimal( 6.50);
            theWinning1.Time = DateTime.Now;
            theWinning1.HeadImgUrl = "/app/Content/Images/redpack/xiaohong.jpg";
            list.Add(theWinning1);     
            Marketing_TheWinning theWinning2 = new Marketing_TheWinning();
            theWinning2.Nickname = "测试数据";
            theWinning2.HeadImgUrl = "/app/Content/Images/redpack/shuju.jpg";
            theWinning2.Denomination = Convert.ToDecimal(5.00);
            theWinning2.Time = DateTime.Now;
            list.Add(theWinning2);
            return Json(list, JsonRequestBehavior.AllowGet);

        }
        public ActionResult MyPrizeRecord(int Tid = 0)
        {
            ViewBag.Tid = Tid;
            return View();

        }
       

        public ActionResult MyPrizeRecordHtml(int Tid = 0)
        {
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.MyPrizeRecord.Replace(" ", "+");
            return Json(data);
        }
        //活动规则
        public ActionResult GetRuleHtml(int Tid = 0)
        {
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.ActivityRuleState.Replace(" ", "+");
            return Json(data);
        }


        public JsonResult GetInFormHtml(int aId)
        {
          Marketing_Activity aModel=_MarketService.GetActivityModel(aId);
            // id =12;
          var model = _MarketService.GetTemplateModel(aModel.TemplateID.Value);
            string data = model.GetInForm.Replace(" ", "+");
            return Json(data, JsonRequestBehavior.AllowGet);
        }



        //奖品领取成功
        public ActionResult GetFinished(int aId, DateTime time,decimal denomination = 0)
        {
            ViewBag.Aid = aId;
            ViewBag.Denomination = denomination;
            ViewBag.Time=time;
         
            return View();
        }
        public ActionResult WithoutView()
        {
            return View();
        }
        public ActionResult GetFinishedHtml(int Tid)
        {
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetInForm.Replace(" ", "+");
            return Json(data);
        }

        public ActionResult PrizeDetailsShowHtml(int Tid) 
        {
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.PrizeDetailsShow.Replace(" ","+");
            return Json(data);
        }

        //中奖明细
        public ActionResult PrizeDetailsShow(string time, int tId = 0 )
        {
            ViewBag.Time=time;
            UserScanQRInfoModel User = (Session["user"] as UserScanQRInfoModel);
            ViewBag.Tid = User.TId;
            ViewBag.Denomination=(Session["user"] as UserScanQRInfoModel).Denomination;
            ViewBag.eName = _MarketService.GetActivityModel(User.Aid).EnterpriseName;
            return View();
        }
    }
}